//
//  HMUserAccountModel.m
//  OC新浪微博
//
//  Created by wyman on 16/4/12.
//  Copyright © 2016年 wyman. All rights reserved.
//

#import "HMUserAccountModel.h"

#import "HMNetworkTool.h"
@implementation HMUserAccountModel

static HMUserAccountModel *_instance;
/** 是为当前对象分配内存空间，所有方法都会最终调用的方法 */
/**
 无论如何实例化，在内存中都最多保留一个副本，对象应该保存在静态区
 静态区中的对象，是在整个程序结束后，才会被销毁。
 */

//定义属性  是否登录
-(BOOL)userLogin
{
//    [self loadUserInfo];

    return self.userAccount!=nil;
}



+(HMUserAccountModel *)sharedInstance
{


    return [[self alloc]init];
}

+ (id)allocWithZone:(struct _NSZone *)zone
{
    //    return nil;
    // 懒加载，不能保证多线程并发的实例化是唯一的
    // 加互斥锁，性能非常糟糕。苹果强烈不建议程序员使用！
    //    @synchronized(self) {
    //        if (_instance == nil) {
    //            _instance = [super allocWithZone:zone];
    //        }
    //    }
    // dispatch_once能够确保块代码中的操作只被执行一次
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        // block中的代码只能被执行一次
        _instance = [super allocWithZone:zone];
        
        
    });
    return _instance;
}

-(instancetype)init{
    if (self = [super init]) {
        self.userAccount = [self loadUserAccount];
    }
    return _instance;
}
-(void)loadAccessToken:(NSString *)code withblock:(void(^)(HMUserAccount *userAccount,NSError *error))onetokenblock{
    
    NSString *urlString = access_tokenString;
    
    //参数
    NSDictionary *paranms = @{
                              @"client_id" : client_id,
                              @"client_secret":client_secret,
                              @"grant_type":@"authorization_code",
                              @"code":code,
                              @"redirect_uri":redirect_uri,
                              };
    
    
    //发送请求
    [[HMNetworkTool sharedInstance] POST:urlString parameters:paranms progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *responseObject) {
        HMLog(@"请求成功");
        self.userAccount = [HMUserAccount initWithDict:responseObject];
        
        //保存,归档
        [self saveUserInfo];
        
        onetokenblock(self.userAccount,nil);
        //建立模型  保存起来
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        HMLog(@"请求失败%@",error);
        onetokenblock(self.userAccount,error);

    }];
    
 
}

//获取用户信息

-(void)loadUserInfoBlock:(void (^)(NSError *))infoblock
{

    NSDictionary *paranm = @{
                                  @"access_token" : self.userAccount.access_token,
                                 
                                  @"uid":self.userAccount.uid,
                                  };
    
    //发送请求,获取用户信息
        [[HMNetworkTool sharedInstance]GET:@"https://api.weibo.com/2/users/show.json" parameters:paranm progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *responseObject) {
            //保存属性信息
            self.userAccount.avatar_large = responseObject[@"avatar_large"];
            self.userAccount.screen_name = responseObject[@"screen_name"];
            
            [self saveUserInfo];

            infoblock(nil);
            //保存到沙盒
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            infoblock(error);

        }];
}

//归档
-(HMUserAccount *)loadUserAccount
{

    HMUserAccount *userAccount = [NSKeyedUnarchiver unarchiveObjectWithFile:accountPath];
    
    //判断是否过去
    if (userAccount && [userAccount.expiresDate compare:[NSDate date]] == NSOrderedDescending)
    {
        return userAccount;
    
    }
    
    
    return nil;


}


//归档,存储数据

-(void)saveUserInfo
{
    if (self.userAccount) {
        
        [NSKeyedArchiver archiveRootObject:self.userAccount toFile:accountPath];
    }


}
@end
